package com.sumer.psychology.blog.infrastructure.messaging.rabbitmq;

import com.sumer.psychology.blog.infrastructure.persistence.mongo.MongoBlogRepository;
import com.sumer.psychology.blog.infrastructure.persistence.mongo.MongoCategoryListRepository;
import com.sumer.psychology.blog.infrastructure.persistence.redis.RedisBlogRepository;
import com.sumer.psychology.common.notification.NotificationReader;
import com.sumer.psychology.common.port.adapter.messaging.Exchanges;
import com.sumer.psychology.common.port.adapter.messaging.rabbitmq.ExchangeListener;
import org.apache.commons.lang3.StringUtils;

/**
 * 监听Blog删除
 * <p/>
 * User: zhenguang.zhu
 * Date: 2014/8/27
 * Time: 14:01
 */
public class BlogDeletedEventListener extends ExchangeListener {
    private MongoBlogRepository mongoBlogRepository;
    private MongoCategoryListRepository mongoCategoryListRepository;

    public BlogDeletedEventListener(MongoBlogRepository mongoBlogRepository,
                                    MongoCategoryListRepository mongoCategoryListRepository) {
        this.mongoBlogRepository = mongoBlogRepository;
        this.mongoCategoryListRepository = mongoCategoryListRepository;
    }

    @Override
    protected String exchangeName() {
        return Exchanges.DEFAULT_EXCHANGE_NAME;
    }

    @Override
    protected void filteredDispatch(String aType, String aTextMessage) {
        NotificationReader reader = new NotificationReader(aTextMessage);
        String blogId = reader.eventStringValue("blogId.identity");

        if (StringUtils.isNotBlank(blogId)) {
            mongoBlogRepository.removeOne(blogId);
            mongoCategoryListRepository.removeBlog(blogId);
        }
    }

    @Override
    protected String[] listensTo() {
        return new String[]{"com.sumer.psychology.blog.domain.model.BlogDeletedEvent"};
    }
}
